import React, { useEffect, useMemo, useState, useContext } from 'react';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { DatePicker, Form, Input, Select, Tooltip, TreeSelect, message, Button } from 'antd';
import { UploadFormCommon } from '@/components/UploadForm';
import { UpdateAssetView } from './UpdateAssetView';
import { downloadTemplate, getFileNameNotType, getTenantID, splitFileUrl } from '@/utils';
import MyIcon from '@/components/MyIcon';
import moment from 'moment';
import { IAssetListActionEnum } from './useManageReducer';
import { TagSelectNew } from '@/components/TagSelectNew';
import { AssetListManageContext } from '../mconfig';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const getUpdateConfig = ({ pageType, record, openAssetModalStatus, assetForm, openUploadModalStatus, setShowInfoDrawer }) => {
  const { assetListDispatch } = useContext(AssetListManageContext);

  /** 变动类型 */
  const [assetChangeTypeState, setAssetChangeTypeState] = useState<any>(null);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 切换表单 */
  useEffect(() => {
    // 回填表单
    if (Object.keys(record).length !== 0) {
      assetForm.setFieldsValue({
        ...record,
        createTime: moment(record?.createTime),
      });
      setAssetChangeTypeState(record?.changeType);
    }
  }, [record]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: assetForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            // required: true,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: true,
            autoComplete: 'off',
            colSpan: 0,
          },
          // {
          //   field: `changeType`,
          //   label: `变动类型`,
          //   component: 'Select',
          //   disabled: disabled,
          //   required: !disabled,
          //   placeholder: '请选择',
          //   colSpan: 2,
          //   options: [
          //     { value: '2', name: '分类信息变动' },
          //     { value: '1', name: '重要信息变动' },
          //     { value: '0', name: '一般信息变动' },
          //   ],
          //   fieldNames: {
          //     label: 'name',
          //     value: 'value',
          //   },
          //   onChange: (value) => {
          //     console.log('value', value);
          //     setAssetChangeTypeState(value);
          //     assetListDispatch({
          //       type: IAssetListActionEnum.SELECT_ASSET,
          //       payload: [],
          //     });
          //   },
          // },
          {
            field: `changeType`,
            label: `变动类型`,
            component: 'Render',
            required: pageType == 'detail' ? false : true,
            colSpan: 2,
            render: (text: string | number) => {
              if (pageType == 'detail') {
                return (
                  <Form.Item name="changeType" style={{ cursor: 'not-allowed' }}>
                    {text == 0 ? '一般信息变动' : text == 1 ? '重要信息变动' : text == 2 ? '分类信息变动' : ''}
                  </Form.Item>
                );
              } else {
                return (
                  <TagSelectNew
                    formLabel=""
                    formName="changeType"
                    formRequired={pageType == 'detail' ? false : true}
                    radioDisabled={pageType == 'detail' ? true : false}
                    radioList={[
                      { value: '0', name: '一般信息变动' },
                      { value: '1', name: '重要信息变动' },
                      // { value: '2', name: '分类信息变动' },
                    ]}
                    onChange={(value: string | number) => {
                      setAssetChangeTypeState(value);
                      assetListDispatch({
                        type: IAssetListActionEnum.SELECT_ASSET,
                        payload: [],
                      });
                    }}
                    defalultKeys={text || ''}
                  />
                );
              }
            },
          },
          {
            field: `applyInfo`,
            label: `申请理由`,
            component: 'Input',
            colSpan: 2,
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            disabled: disabled,
            colSpan: 2,
            placeholder: '请选择',
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={assetForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      // hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
          // {
          //   field: `handlePerson`,
          //   label: `维修人`,
          //   component: 'Input',
          //   disabled: true,
          //   placeholder: '自动带出',
          //   required: false,
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          // },
          // {
          //   field: `handleTime`,
          //   label: `完成时间`,
          //   component: 'Input',
          //   required: false,
          //   disabled: true,
          //   placeholder: '自动带出',
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          // },
          // {
          //   field: `newMaintenTime`,
          //   label: `下次维保日期`,
          //   required: !disabled,
          //   component: 'Input',
          //   disabled: disabled,
          //   colSpan: 1,
          //   placeholder: '自动带出',
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          // },
          // {
          //   field: `handleNumber`,
          //   label: `维修人电话`,
          //   component: 'Input',
          //   // required: true,
          //   placeholder: '自动带出',
          //   disabled: disabled,
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          // },
          // {
          //   field: `spend`,
          //   label: `维修花费`,
          //   component: 'InputNumber',
          //   // required: true,
          //   placeholder: '自动带出',
          //   min: 0,
          //   disabled: disabled,
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          // },
          // {
          //   field: `content`,
          //   label: `维修原因及内容`,
          //   component: 'InputTextArea',
          //   disabled: disabled,
          //   placeholder: '请输入',
          //   required: !disabled,
          //   colSpan: 2,
          //   allowClear: true,
          //   showCount: true,
          //   maxLength: 200,
          //   autoSize: { minRows: 2, maxRows: 4 },
          // },
          // {
          //   field: `applyFile`,
          //   label: `相关附件`,
          //   component: 'Render',
          //   disabled: disabled,
          //   placeholder: '请选择',
          //   render: (text, record) => {
          //     const fileName = 'applyFile';
          //     return (
          //       <>
          //         {!disabled ? (
          //           <UploadFormCommon
          //             form={assetForm}
          //             fileFormName={fileName}
          //             spanCol={24}
          //             inRowProportion={24}
          //             name={'attachFile'}
          //             required={false}
          //             // accept={'.doc|.docx'}
          //             url={'/assetInfo/uploadFile'}
          //             downloadUrl={'/assetInfo/downloadFile'}
          //             fileFormDelName={'delFile'}
          //             delFunc={(delFilePath: string) => {
          //               console.log('--- w文件url', delFilePath);
          //             }}
          //             // maxFile={1}
          //             defaultFiles={text}
          //             // hintTitle={'且只能上传 1 个！'}
          //             fieldBusiPath={'assetFile'}
          //           >
          //             上传
          //           </UploadFormCommon>
          //         ) : (
          //           <div
          //             style={{
          //               height: '100%',
          //               display: 'flex',
          //               alignItems: 'center',
          //               marginLeft: '8px',
          //             }}
          //           >
          //             {record?.[fileName]
          //               ? splitFileUrl(record?.[fileName])?.map((e, i) => {
          //                   return (
          //                     <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
          //                       <a
          //                         onClick={() => {
          //                           message.success('下载中，请稍后...');
          //                           downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
          //                         }}
          //                       >
          //                         <MyIcon type="icon-file-text-fill" />
          //                         &nbsp;
          //                         {getFileNameNotType(e.attachName, 8)}
          //                       </a>
          //                     </Tooltip>
          //                   );
          //                 })
          //               : '--'}
          //           </div>
          //         )}
          //       </>
          //     );
          //   },
          // },
          // {
          //   field: `handleProve`,
          //   label: `回执单`,
          //   component: 'Render',
          //   disabled: false,
          //   placeholder: '请选择',
          //   ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          //   render: (text, record) => {
          //     const fileName = 'handleProve';
          //     return (
          //       <>
          //         <div
          //           style={{
          //             height: '100%',
          //             display: 'flex',
          //             alignItems: 'center',
          //             marginLeft: '8px',
          //           }}
          //         >
          //           {record?.[fileName]
          //             ? splitFileUrl(record?.[fileName])?.map((e, i) => {
          //                 return (
          //                   <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
          //                     <a
          //                       onClick={() => {
          //                         message.success('下载中，请稍后...');
          //                         downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
          //                       }}
          //                     >
          //                       <MyIcon type="icon-file-text-fill" />
          //                       &nbsp;
          //                       {getFileNameNotType(e.attachName, 8)}
          //                     </a>
          //                   </Tooltip>
          //                 );
          //               })
          //             : '--'}
          //         </div>
          //       </>
          //     );
          //   },
          // },
        ],
      },
      {
        key: 'accept-procurement0',
        title: '',
        fieldCustomDom:
          assetChangeTypeState == '0' ? (
            <UpdateAssetView
              pageType={pageType}
              openAssetModalStatus={openAssetModalStatus}
              openUploadModalStatus={openUploadModalStatus}
              changeType={0}
              setShowInfoDrawer={setShowInfoDrawer}
            />
          ) : null,
      },
      {
        key: 'accept-procurement1',
        title: '',
        fieldCustomDom:
          assetChangeTypeState == '1' ? (
            <UpdateAssetView
              pageType={pageType}
              openAssetModalStatus={openAssetModalStatus}
              openUploadModalStatus={openUploadModalStatus}
              changeType={1}
              setShowInfoDrawer={setShowInfoDrawer}
            />
          ) : null,
      },
      // {
      //   key: 'accept-procurement2',
      //   title: '',
      //   fieldCustomDom:
      //     assetChangeTypeState == '2' ? (
      //       <UpdateAssetView
      //         pageType={pageType}
      //         openAssetModalStatus={openAssetModalStatus}
      //         openUploadModalStatus={openUploadModalStatus}
      //         changeType={2}
      //         setShowInfoDrawer={setShowInfoDrawer}
      //       />
      //     ) : null,
      // },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
